﻿namespace nhappend
{
    using System;
    using Data;
    using log4net.Appender;
    using log4net.Core;
    using log4net.Util;

    public class NHibernateLogAppender : BufferingAppenderSkeleton
    {
        private readonly ILogMessageRepository messageRepository;

        public NHibernateLogAppender() : this(new LogMessageRepository())
        {
        }

        public NHibernateLogAppender(ILogMessageRepository repository)
        {
            messageRepository = repository;
        }

        protected override void SendBuffer(LoggingEvent[] events)
        {
            if (messageRepository == null) return;

            if (events == null) return;
            var messages = events.ToEntities();

            foreach (var message in messages)
            {
                try
                {
                    messageRepository.Create(message);
                }
                catch(Exception ex)
                {
                    LogLog.Error("Could not insert message to repository.", ex);
                }
            }
        }
    }
}